﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using Microsoft.SharePoint;
using System.Collections;
using JM.JCY.Common;

namespace JM.JCY.SharePointComponent.Committee.CreateCommittee
{
    public partial class CreateCommitteeUserControl : UserControl
    {
        public int _userId
        {
            set { ViewState["_userId"] = value; }
            get { return (int)ViewState["_userId"]; }
        }

        public int _newId
        {
            set { ViewState["_newId"] = value; }
            get { return (int)ViewState["_newId"]; }
        }

        public string _userName
        {
            set { ViewState["_userName"] = value; }
            get { return (string)ViewState["_userName"]; }
        }
        static string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ApplicationContext.Current.GetKeyValue("userId") != null)
            {
                _userId = Int32.Parse(ApplicationContext.Current.GetKeyValue("userId").ToString());
                _userName = ApplicationContext.Current.UserName;
            }
            if (!IsPostBack)
            {

                using (UserManagementProxy userProxy = new UserManagementProxy())
                {
                    DataSetUserManagement.T_UserInfoDataTable userDT = userProxy.GetUser(0, string.Empty);
                    if (userDT.Rows.Count > 0)
                    {
                        box1View.DataSource = userDT;
                        box1View.DataTextField = "UserName";
                        box1View.DataValueField = "ID";
                        box1View.DataBind();
                    }
                }

            }
        }

        protected void imgSavePublish_Click(object sender, ImageClickEventArgs e)
        {
            SaveCommittee();
            Response.Redirect("/MyCommittee/default.aspx?CommitteeId=" + _newId);
        }

        

        private void SaveCommittee()
        {
            var arrUserCol = new ArrayList();
            // Create committee doc and add users
            CreateDocumentLibrary(this.txtName.Text, this.txtDesc.Text, SPListTemplateType.DocumentLibrary);
            CreateDocumentLibrary(this.txtName.Text + " 讨论版", this.txtDesc.Text, SPListTemplateType.DiscussionBoard);

            using (UserManagementProxy proxy = new UserManagementProxy())
            {
                var newCommitteeDT = new CommitteeDataSet.T_CommitteeDataTable();
                var newMemberDT = new CommitteeDataSet.T_UserCommitteeDataTable();
                var newCommitteeRow = newCommitteeDT.NewT_CommitteeRow();
                newCommitteeRow.CommitteeName = this.txtName.Text;
                newCommitteeRow.CommitteeDescription = this.txtDesc.Text;
                newCommitteeRow.Creator = _userId;
                newCommitteeRow.IsDeleted = false;
                JCY.Common.JCYUtility.UpdateCommonFields(newCommitteeRow, "admin");
                newCommitteeDT.AddT_CommitteeRow(newCommitteeRow);
                proxy.UpdateCommittee(newCommitteeDT);

                _newId = newCommitteeDT[0].ID;
                // update user committee

                string s = Request.Form[box2View.UniqueID];
                if (!string.IsNullOrEmpty(s))
                {
                    foreach (var item in s.Split(','))
                    {
                        if (Int32.Parse(item) != _userId)
                            AddUserToCommittee(newMemberDT, Int32.Parse(item), _newId, false);
                        else
                            AddUserToCommittee(newMemberDT, Int32.Parse(item), _newId, true);
                        // add user into group
                        SPWeb web = SPContext.Current.Web;
                        string selectUser = proxy.GetUser(Int32.Parse(item), string.Empty)[0].UserName;
                        SPUser spUser = web.EnsureUser(selectUser);
                        AddUserToGroup(spUser, this.txtName.Text);

                        // add all user into arr
                        arrUserCol.Add(item);
                    }

                    // check whether creator is in list
                    if (!arrUserCol.Contains(_userId.ToString()))
                    {
                        AddUserToCommittee(newMemberDT, _userId, _newId, true);
                        // add user into group
                        SPWeb web = SPContext.Current.Web;
                        string selectUser = proxy.GetUser(_userId, string.Empty)[0].UserName;
                        SPUser spUser = web.EnsureUser(selectUser);
                        AddUserToGroup(spUser, this.txtName.Text);
                    }

                    proxy.UpdateUserComittee(newMemberDT);
                }
            }


        }

        private void AddUserToCommittee(CommitteeDataSet.T_UserCommitteeDataTable newMemberDT, int userId, int committeeId, bool isAdmin)
        {
            var memberRow = newMemberDT.NewT_UserCommitteeRow();
            memberRow.UserId = userId;
            memberRow.CommitteeId = committeeId;
            if (isAdmin)
                memberRow.IsAdmin = true;
            else
                memberRow.IsAdmin = false;
            memberRow.IsDeleted = false;
            JCY.Common.JCYUtility.UpdateCommonFields(memberRow, "admin");
            newMemberDT.AddT_UserCommitteeRow(memberRow);

        }

        private void CreateDocumentLibrary(string docName, string docDesc, SPListTemplateType templateType)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb myWeb = site.AllWebs[JCYConstant.SiteName.MyCommittee])
                    {
                        myWeb.AllowUnsafeUpdates = true;
                        myWeb.Lists.Add(docName, docDesc, templateType);
                        myWeb.Update();
                     

                        //// break permission from parent 
                        SPList newDoc = myWeb.Lists[docName];
                        if (!newDoc.HasUniqueRoleAssignments)
                            newDoc.BreakRoleInheritance(true);
                        SPRoleAssignmentCollection assignmentCol = newDoc.RoleAssignments;
                        for (int i = assignmentCol.Count - 1; i >= 0; i--)
                        {
                            assignmentCol.Remove(i);
                        }

                        // create group and set group owner
                        if (!IsExistGroup(myWeb, docName))
                        {
                            SPUser owner = myWeb.EnsureUser(_userName);
                            myWeb.SiteGroups.Add(docName, owner, null, "Contributors to " + docName);
                        }

                        SPGroup newContribGroup = myWeb.SiteGroups[docName];
                        SPRoleDefinition contribRole = myWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        SPRoleAssignment contribRoleAssignment = new SPRoleAssignment(newContribGroup);
                        contribRoleAssignment.RoleDefinitionBindings.Add(contribRole);
                        newDoc.RoleAssignments.Add(contribRoleAssignment);

                        myWeb.AllowUnsafeUpdates = false;
                    }
                }
            });


    




        }

        public bool IsExistGroup(SPWeb web, string groupname)
        { 
            bool exist = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb myWeb = site.AllWebs[JCYConstant.SiteName.MyCommittee])
                    {
                        SPGroupCollection groups = myWeb.SiteGroups;
                        foreach (SPGroup grouplist in groups)
                        {
                            if (grouplist.ToString().ToLower() == groupname.ToLower())
                                exist = true;
                        }
                    }
                }
            });

          

            return exist;

        }
        //public bool IsExistGroup(SPWeb web, string groupname)
        //{
        //    try
        //    {
        //        SPGroupCollection groups = web.SiteGroups;
        //        foreach (SPGroup grouplist in groups) //判断组是否存在
        //        {
        //            if (grouplist.ToString().ToLower() == groupname.ToLower())
        //                return true;
        //        }
        //        return false;
        //    }
        //    catch (Exception)
        //    {
        //        throw;
        //    }
        //}

        public void AddUserToGroup(SPUser user, string groupname)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyCommittee])
                    {
                        web.AllowUnsafeUpdates = true;
                        if (!IsExistUser(user, groupname))
                        {
                            
                            web.SiteGroups[groupname].AddUser(user);
                        }
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        public bool IsExistUser(SPUser user, string groupname)
        {
            bool exist = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyCommittee])
                    {
                        SPUserCollection users = web.SiteGroups[groupname].Users;
                        foreach (SPUser userlist in users)
                        {
                            if (userlist.ToString().ToLower() == user.LoginName.ToLower())
                                exist = true;
                        }
                    }
                }
            });


            return exist;

        }

        //public bool IsExistUser(SPUser user, string groupname)
        //{
        //    try
        //    {
        //        SPWeb web = SPContext.Current.Web;
        //        SPUserCollection users = web.SiteGroups[groupname].Users;
        //        foreach (SPUser userlist in users)
        //        {
        //            if (userlist.ToString().ToLower() == user.LoginName.ToLower())
        //                return true;
        //        }
        //        return false;
        //    }
        //    catch (Exception)
        //    {
        //        throw;
        //    }
        //}

        protected void imgCancel_Click(object sender, ImageClickEventArgs e)
        {

            Response.Redirect(SPContext.Current.Site.Url);
        }
    }
}
